package top.dbpanda.cmsjpa.learn.thread.semaphore;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Semaphore;

/**
 * 使用信号量实现线程通信
 *
 * @author 20018954
 */
public class TestSemaphore {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        //同一时间，只允许3个线程并发访问
        Semaphore semaphore = new Semaphore(3);
        //创见8个线程
        for (int i = 0; i < 8; i++) {
            final int threadNo = i;
            //execute() 方法重写了run()方法的Runable对象
            executor.execute(() -> {
                        try {
                            //同一时间，只能有3个线程获取允许执行
                            semaphore.acquire();
                            System.out.println("得到许可并执行的线程:" + threadNo);
                            Thread.sleep((long) (Math.random() * 10000));
                            //得到许可的线程执行完毕后，将机会转让给其他线程
                            semaphore.release();
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
            );
        }
    }
}
